package live.jipiao.dao;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.print.Doc;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import live.common.AirParam;
import live.common.DBHelper;
import live.common.Format;
import live.common.Page;
import live.common.Verifystring;
import live.jipiao.entity.RiseCabinChange;

public class RiseChangeManger {
	private XmlFormart xfm = new XmlFormart();
	
	
	public boolean returnValRiseCabin(RiseCabinChange rc){
		boolean valState=false;
		try {
			String web_Result = returnWebServiceResult(rc);
			if(Format.getInstance().isNotNullOrEmpty(web_Result)){
				Document doc = DocumentHelper.parseText(web_Result);

				Element element = doc.getRootElement();

				String is_success = element.elementText("is_success");
				
				String desc=null,cabinNo=null,state=null;
				if(is_success.equals("F")){
					desc=element.elementText("error");
				}else{
					state=element.elementText("State");
					if(state.equals("T")){
						cabinNo=element.elementText("CabinNo");
					}
				}
				rc.setCabinNo(cabinNo);
				rc.setState(state);
				addRiseInfo(rc,desc);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return valState;
	}
	
	/**
	 * 添加新的升舱记录信息
	 * @param rc
	 * @param desc
	 */
	private void addRiseInfo(RiseCabinChange rc,String desc){
		String sql = "{call addPlaneRise(?,?,?,?,?,?,?,?,?,?,?,?)}";
		Object[] objs = new Object[12];
		objs[0]=rc.getOrderNo();
		objs[1]=rc.getPassengers();
		objs[2]=rc.getFlightDate();
		objs[3]=rc.getFlightNo();
		objs[4]=Format.getInstance().isNotNullOrEmpty(rc.getRemarks())?rc.getRemarks():null;
		objs[5]=rc.getNoticeStatus();
		objs[6]="rise";
		objs[7]=rc.getMemberNo();
		objs[8]=rc.getCabin();
		objs[9]=desc;
		objs[10]=rc.getCabinNo();
		objs[11]=rc.getState();
		update(sql, objs);
	}
	
	private int update(String sql ,Object...args){
		DBHelper dh = DBHelper.getInstance();
		try {
			dh.update(sql,args);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{dh.close();}
		return 0;
	}
	
	/**
	 * 获取接口返回信息
	 * @param rc
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	private String returnWebServiceResult(RiseCabinChange rc)
			throws UnsupportedEncodingException, IOException {
		TreeMap treemap = xfm.returnPublicPostData(AirParam.RISE_CABIN.toString());
		treemap.put("orderNo", rc.getOrderNo());
		treemap.put("passengers", rc.getPassengers());
		treemap.put("flightDate", rc.getFlightDate());
		treemap.put("flightNo", rc.getFlightNo());
		treemap.put("cabin", rc.getCabin());
		treemap.put("remarks", Format.getInstance().isNotNullOrEmpty(rc.getRemarks())?rc.getRemarks():null);
		String sign = new Verifystring().returnAirMd5Hex(treemap);
		treemap.put("sign", sign);
		String result = WebServicesSub.getInstance().returnResult(treemap);
		return result;
	}
	
	/**
	 * 获取用户需要支付差额的升舱数据
	 * @param type
	 * @param page
	 * @param memberNo
	 * @return
	 */
	public List<RiseCabinChange> getRiseList(String type,Page page,String memberNo){
		String execSql = "{call pro_Common_PageView(?,?,?,?)}";
		String sql = new StringBuffer("SELECT * FROM Plane_ChangeRise WHERE 1=1 AND memberNo='").append(memberNo).append("' AND changeRise='rise' AND state IN ('2','7') ORDER BY ID DESC").toString();
		Object[] args = new Object[4];
		args[0]=sql.toString();
		args[1]=page.getPageIndex();
		args[2]=page.getPageSize();
		args[3]="";
		DBHelper dh = DBHelper.getInstance();
		dh.setBeanClass(RiseCabinChange.class);
		List list=null;
		try {
			list = dh.queryRecords(sql);
			page.setRecordCount(dh.returnOutParam(execSql, args));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dh.close();
		return list;
	}
	
	/**
	 * 升舱差额支付
	 * @param orderNo
	 */
	public boolean payRiseOrder(String orderNo){
		RiseCabinChange rc = getRiseOrder(orderNo);
		TreeMap treemap = xfm.returnPublicPostData(AirParam.RISE_CABIN_AUTO_PAY.toString());
		treemap.put("orderNo", rc.getOrderNo());
		treemap.put("cabinNo", rc.getCabinNo());
		treemap.put("autopaymode", "1");
		treemap.put("paytype", "A");
		String sign = new Verifystring().returnAirMd5Hex(treemap);
		treemap.put("sign", sign);
		String result = WebServicesSub.getInstance().returnResult(treemap);
		return readerPayResult(result,orderNo);
	}
	
	private boolean readerPayResult(String xmlString,String orderNo) {

		boolean flag = true;

		try {

			Document doc = DocumentHelper.parseText(xmlString);

			Element element = doc.getRootElement();

			String is_success = element.elementText("is_success");

			String pay_status = element.element("response").elementText(
					"Pay_Status");
			
			if (is_success.trim().equals("F") || pay_status.trim().equals("F")) {
				
				flag = false;
				
			}else {
				
				flag = true;
			}


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 获取详细信息
	 * @param orderNo
	 * @return
	 */
	public RiseCabinChange getRiseOrder(String orderNo){
		RiseCabinChange rcc=null;
		DBHelper dh = DBHelper.getInstance();
		dh.setBeanClass(RiseCabinChange.class);
		String sql = "SELECT * FROM Plane_ChangeRise WHERE 1=1 AND cabinNo='"+orderNo+"'";
		try {
			rcc=(RiseCabinChange)dh.query(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dh.close();
		return rcc;
	}
	
	public static String returnSubject_Desc(RiseCabinChange item){
		
		return new StringBuffer("升舱支付[").append(item.getBalance()).append("元]").append(",").append(item.getCabinNo()).append(",").append(item.getFlightNo()).toString();
	}
	
}
